<template>
    <div class="editor-render">

        <!-- 背景 -->
        <!-- <div class="editor-render-mask" v-if="activePiece">
            <img crossOrigin="anonymous" v-for="piece in pieces" :key="piece.canvas_name" :src="$getImageUrl(piece.mask_image, 'largest')" v-show="activePiece.canvas_name == piece.canvas_name">
        </div> -->

        <!-- 背景 -->
        <div class="editor-render-mask" :name="activePiece.canvas_name">
            <svg width="660px" height="660px" viewBox="0 0 660 660" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                    <path d="M0,660 L0,26.2735375 C8.64477539,23.5913195 15.0941162,20.898367 21.3480225,18.1946801 L22.305,18 C110.812,36.779 217.458,47.749 332.266,47.749 C447.075,47.749 553.72,36.779 642.227,18 C648.229964,20.4614111 654.820964,23.2192569 662,26.2735375 L662,660 L0,660 Z" id="Fill-1" :fill="necklabelColor"></path>
                    <g id="编组" transform="translate(-2.000000, -0.000100)">
                        <path d="M0,0 L0,26.2735375 C8.64477539,23.5913195 15.0941162,20.898367 21.3480225,18.1946801 L22.305,18 C110.812,36.779 217.458,47.749 332.266,47.749 C447.075,47.749 553.72,36.779 642.227,18 C648.229964,20.4614111 654.820964,23.2192569 662,26.2735375 L662,0 L2,0 Z" id="Fill-1" fill="#FFFFFF"></path>
                        <path d="M2.8046875,86.9244164 L22.0778224,90.956961 C110.666322,109.514003 217.064602,120.33014 331.498241,120.33014 C446.39786,120.33014 553.196348,109.425027 642,90.7300724 L661.097656,86.3140648" id="Stroke-7" stroke="#BDBDBD" stroke-linecap="round"></path>
                        <path d="M4.33886719,72.0259789 L22.0778224,75.3283174 C110.666322,93.8853597 217.064602,104.701496 331.498241,104.701496 C446.39786,104.701496 553.196348,93.7963838 642,75.1014288 L659.949219,70.8584984" id="Stroke-7备份" stroke="#BDBDBD" stroke-linecap="round" stroke-dasharray="0.999,1.998"></path>
                        <line x1="642.645859" y1="17.9005822" x2="662.5" y2="26.5001" id="路径-2" stroke="#BDBDBD" stroke-linecap="round"></line>
                        <line x1="1" y1="18.0003209" x2="21.5" y2="26.5001" id="路径-2备份-2" stroke="#BDBDBD" stroke-linecap="round" transform="translate(11.500000, 22.500321) scale(-1, 1) translate(-11.500000, -22.500321) "></line>
                        <path d="M0,129.7051 L2.58459473,88.060891 L2.693,86.7121 C3.701,63.3871 10.267,40.8241 21.762,19.0211 L22.305,18.0001 C110.812,36.7791 217.458,47.7491 332.266,47.7491 C447.075,47.7491 553.72,36.7791 642.227,18.0001 C651.815,37.4841 657.318,52.5201 658.734,63.1081 C659.869,71.5901 661.4,82.1681 661.724,86.3131 C661.724,86.5264304 661.724,86.8937637 661.724,87.4151 L664,132.6331" id="Stroke-1" stroke="#BDBDBD" stroke-linecap="round"></path>
                    </g>

                    <g id="编组-113" transform="translate(168.000000, 228.000000)" v-if="!necklabelInfo.active" :fill="activeColor.is_white ? '#fff' : '#000'" :stroke="activeColor.is_white ? '#fff' : '#000'">
                        <g id="编组-112" transform="translate(33.000000, 190.000000)">
                            <g id="编组备份-3" transform="translate(47.000000, 88.000000)">
                                <g id="编组-46" transform="translate(1.637574, 5.458580)">
                                    <g id="编组-38">
                                        <path d="M0,0 L3.80847862,14.6368522 C3.93717632,15.1306968 4.37788484,15.475074 4.88240146,15.475074 L17.8884398,15.475074 C18.3886304,15.475074 18.8271759,15.1361718 18.9591181,14.6478022 L22.9260355,0" id="Stroke-1" fill="none" stroke-width="2" stroke-linecap="round"></path>
                                        <path d="M12.6911982,9.88685281 C12.6911982,10.599351 12.1415875,11.1764423 11.4630178,11.1764423 C10.784448,11.1764423 10.2348373,10.599351 10.2348373,9.88685281 C10.2348373,9.17435461 10.784448,8.59726331 11.4630178,8.59726331 C12.1415875,8.59726331 12.6911982,9.17435461 12.6911982,9.88685281 Z" id="Stroke-5"></path>
                                    </g>
                                    <path d="M0.859726331,2.14931583 C2.61035799,2.14931583 2.61035799,3.17153044 4.36045948,3.17153044 C6.11109115,3.17153044 6.11109115,2.14931583 7.86225298,2.14931583 C9.6118243,2.14931583 9.6118243,3.17153044 11.3619258,3.17153044 C13.1130876,3.17153044 13.1130876,2.14931583 14.8647796,2.14931583 C16.617532,2.14931583 16.617532,3.17153044 18.3697542,3.17153044 C20.1225065,3.17153044 20.1225065,2.14931583 21.8752589,2.14931583" id="Stroke-1" stroke-width="2" stroke-linecap="round" transform="translate(11.367493, 2.660423) scale(1, -1) translate(-11.367493, -2.660423) "></path>
                                </g>
                                <g id="编组-45" transform="translate(34.934911, 0.000000)">
                                    <g id="编组-44" transform="translate(1.940828, 1.940828)">
                                        <path d="M10.9171598,2.23606798 L20.2162855,20.8343195 L1.61803399,20.8343195 L10.9171598,2.23606798 Z" id="三角形" fill="none" stroke-width="2"></path>
                                        <path d="M16.181645,12.0265007 C16.6599376,12.3026431 16.8238127,12.9142335 16.5476704,13.3925261 L12.0890905,21.115013 C11.8129481,21.5933056 11.2013577,21.7571808 10.7230651,21.4810384 C10.2447725,21.204896 10.0808973,20.5933056 10.3570397,20.115013 L14.8156196,12.3925261 C15.0917619,11.9142335 15.7033523,11.7503583 16.181645,12.0265007 Z M13.8188973,6.94584368 C14.29719,7.22198605 14.4610651,7.83357646 14.1849227,8.31186908 L6.99705292,20.7616248 C6.72091054,21.2399174 6.10932014,21.4037926 5.63102752,21.1276502 C5.15273489,20.8515078 4.98885974,20.2399174 5.26500211,19.7616248 L12.4528719,7.31186908 C12.7290143,6.83357646 13.3406047,6.6697013 13.8188973,6.94584368 Z" id="形状结合" stroke="none"></path>
                                    </g>
                                </g>
                                <g id="编组-44备份" transform="translate(68.899408, 0.000000)">
                                    <rect id="矩形" fill="none" stroke-width="2" x="3.72928994" y="3.72928994" width="18.7426036" height="18.7426036" rx="2"></rect>
                                    <circle id="椭圆形" fill="none" stroke-width="2" cx="13.1005917" cy="13.1005917" r="8.82544379"></circle>
                                    <path d="M14.1005917,13.1005917 C14.1005917,13.6530917 13.6530917,14.1005917 13.1005917,14.1005917 C12.5480917,14.1005917 12.1005917,13.6530917 12.1005917,13.1005917 C12.1005917,12.5480917 12.5480917,12.1005917 13.1005917,12.1005917 C13.6530917,12.1005917 14.1005917,12.5480917 14.1005917,13.1005917 Z" id="Stroke-5"></path>
                                </g>
                                <g id="编组-43" transform="translate(102.863905, 0.000000)">
                                    <g id="编组-47" transform="translate(1.637574, 5.458580)">
                                        <path d="M6.78011921,0 L18.0300462,0 C18.5981562,0 19.0957125,0.387357416 19.2435683,0.945626156 L22.8957915,14.7251957 C23.0436473,15.2822169 22.6307553,15.8298817 22.0632588,15.8298817 L0.510050295,15.8298817 C0.106360927,15.8298817 -0.135975396,15.3764053 0.0818205397,15.03084 C1.35117206,13.0210726 4.97394672,7.91494083 9.01758901,7.91494083 L21.090846,7.91494083" id="Stroke-1" fill="none" stroke-width="2" stroke-linecap="round"></path>
                                        <path d="M14.1005917,11.1597633 C14.1005917,11.6959172 13.6663314,12.1301775 13.1301775,12.1301775 C12.5940237,12.1301775 12.1597633,11.6959172 12.1597633,11.1597633 C12.1597633,10.6236095 12.5940237,10.1893491 13.1301775,10.1893491 C13.6663314,10.1893491 14.1005917,10.6236095 14.1005917,11.1597633 Z" id="Stroke-5备份"></path>
                                    </g>
                                </g>
                                <g id="编组-42" transform="translate(137.798817, 0.000000)">
                                    <g id="编组-48" transform="translate(1.015132, 3.275148)">
                                        <circle id="椭圆形备份" fill="none" stroke-width="2" cx="11.7908427" cy="9.82544379" r="8.82544379"></circle>
                                        <path d="M24.0639196,9.7795858 L24.0639196,10.7795858 L-0.263891053,10.7795858 L-0.263891053,9.7795858 L24.0639196,9.7795858 Z" id="矩形" fill="#000000" transform="translate(11.900014, 10.279586) rotate(25.000000) translate(-11.900014, -10.279586) "></path>
                                        <path d="M24.0639196,9.7795858 L24.0639196,10.7795858 L-0.263891053,10.7795858 L-0.263891053,9.7795858 L24.0639196,9.7795858 Z" id="矩形备份-46" fill="#000000" transform="translate(11.900014, 10.279586) scale(1, -1) rotate(25.000000) translate(-11.900014, -10.279586) "></path>
                                    </g>
                                </g>
                            </g>
                            <text id="100%-Pure-Cotton备份" font-size="14" font-weight="normal" line-spacing="22" stroke="none">
                                <tspan x="71.796875" y="49">100% Pure Cotton</tspan>
                            </text>
                            <text id="Made-in-China备份" font-size="14" font-weight="normal" line-spacing="22" stroke="none">
                                <tspan x="82.3623047" y="68">Made in China</tspan>
                            </text>
                            <text id="L备份" font-family="Arial-BoldMT, Arial" font-size="22" font-weight="bold" stroke="none">
                                <tspan x="122.217428" y="20">L</tspan>
                            </text>
                        </g>
                    </g>
                </g>
            </svg>
            <canvas ref="mask"></canvas>
        </div>

        <!-- 网格 -->
        <div class="editor-gridline-line" :style="renderStyle">
            <span v-for="(item, index) in gridlineStyle" :key="index" :style="item"></span>
        </div>

        <!-- 图层 -->
        <div class="editor-render-layer" ref="layer"></div>

        <!-- 边框 -->
        <div class="editor-gridline-border" :style="renderStyle"></div>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import { fabric as Fabric } from "fabric";
import DesignEditor from "@/utils/DesignEditor.js";
import DesignManager from "@/utils/DesignManager.js";
import DesignResource from "@/utils/DesignResource.js";
import DesignUtils from "@/utils/DesignUtils.js";

export default {
    props: {
        zoom: { type: Boolean, default: false },
        gridline: { type: Boolean, default: false },
    },
    data () {
        return {
            scale: 1,
            render: new Map(),
        };
    },
    computed: {
        ...mapGetters("designer", {
            pieces: "getPieces",
            activePiece: "getActivePiece",
            activeDst: "getActiveDst",
            activeModel: "getActiveModel",
            activeColor: "getActiveColor",
            activeSurface: "getActiveSurface",
            necklabelInfo: "getNecklabelInfo",
        }),
        // 渲染器
        renderStyle () {
            if (!this.activePiece) {
                return { display: 'none' }
            } else {
                let piece = this.activePiece;
                return {
                    width: 100 * piece.canvas_width / piece.outer_width + '%',
                    height: 100 * piece.canvas_height / piece.outer_height + '%',
                    left: 100 * piece.canvas_left / piece.outer_width + '%',
                    top: 100 * piece.canvas_top / piece.outer_height + '%',
                    transform: `rotate(${piece.canvas_rotate}deg)`,
                }
            }

        },

        // 网格样式
        gridlineStyle () {
            if (!this.activePiece) {
                // 没有选中
                return [];
            } else if (!this.gridline) {
                // 不打开网格
                return [];
            } else {

                let list = [];
                let size = 100;
                let scale = 1;
                let width = this.activePiece.canvas_width * scale;
                let height = this.activePiece.canvas_height * scale;

                // 数量
                let countX = Math.max(Math.round(width / size) - 1, 0);
                let countY = Math.max(Math.round(height / size) - 1, 0);
                let offsetX = width / (countX + 1);
                let offsetY = height / (countY + 1);

                while (countX > 0) {
                    let x = 100 * (offsetX * countX) / width;
                    list.push({ left: x + '%', top: '0', height: '100%', width: '0' });
                    countX -= 1;
                }

                while (countY > 0) {
                    let y = 100 * (offsetY * countY) / height;
                    list.push({ left: '0', top: y + '%', height: '0', width: '100%' });
                    countY -= 1;
                }

                return list;
            }
        },


        necklabelColor () {

            if (this.activePiece && this.activePiece.canvas_name === 'Neck Label Inner') {
                const color = this.activeColor.color_num;
                const hex = [...DesignUtils.colorRgb(color), 0.85];
                return 'rgba(' + hex.join(',') + ')'
            } else {
                return null;
            }
        }

    },
    watch: {
        zoom () {
            this.init();
        },
        activeSurface () {
            this.init();
        },
        activePiece: {
            immediate: false,
            deep: true,
            handler (newval, oldval) {
                this.updatePiece(newval);
                this.updateMask(newval);
            },
        },

    },
    methods: {

        // 修改背景图
        updateMask (piece, force) {

            const canvas = this.$refs.mask;
            const url = piece.mask_image || '';
            const option = {
                type: "simple",
                form: "editor",
            };

            const cache = JSON.stringify({
                url: url,
                // color: this.activeColor,
            })

            if (!canvas) {
                // 没有canvas
            } else if (!force && canvas.cache == cache) {
                // 缓存相同
            } else {

                // 写画布
                url && DesignResource.loadImage(url, option).then(image => {

                    const rect = canvas.parentNode.getBoundingClientRect();
                    const ctx = canvas.getContext("2d")
                    // 清空画布
                    canvas.cache = cache;
                    canvas.width = rect.width * 2;
                    canvas.height = rect.height * 2;
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
                });

            }

        },

        // 更新打印区
        updatePiece (piece) {

            let render = this.render.get(piece)
            let pieceCache = JSON.stringify(piece);
            let sizesCache = JSON.stringify({
                scale: this.scale,
                canvas_width: piece.canvas_width,
                canvas_height: piece.canvas_height,
                canvas_left: piece.canvas_left,
                canvas_top: piece.canvas_top,
            });

            if (render && sizesCache == render.sizesCache && pieceCache == render.pieceCache) {

                // 数据相同，且已经完成
                // this.updatePieceStage(render);
                if (render.status == "complete") {
                    // 已经完成
                    return Promise.resolve();
                } else {
                    // 正在进行中
                    return new Promise((resolve) => {
                        render.loops.push((e) => resolve());
                    });
                }
            } else if (render && sizesCache == render.sizesCache) {
                // 尺寸相同
                // 更新图层的数据
                return new Promise((resolve) => {
                    render.pieceCache = pieceCache;
                    render.loops.push((e) => resolve());
                    render.editor.renderLayers(piece.layers).then((e) => {
                        render.loops.map((cb) => cb());
                        render.loops = [];
                    });
                });
            } else {
                let option = {
                    canvas_name: piece.canvas_name,
                    canvas_scale: this.scale,
                    canvas_model: "simple",
                    type: piece.type,
                    canvas_width: piece.canvas_width,
                    canvas_height: piece.canvas_height,
                    design_layers: [],
                    onUpdate: (fabric) => {
                        const state = {
                            canvas_name: piece.canvas_name,
                            canvas: fabric.lowerCanvasEl,
                            fabric: fabric,
                            layers: piece.layers.slice(0),
                        };
                        //  触发更新
                        DesignManager.updatePieceState(state);

                        // DesignManager.$emit('update', state)
                    },
                };

                // piece在当前Surface中才展示，不在时，则关闭
                if (!render) {
                    const editor = new DesignEditor(Fabric, null, option);
                    const canvas = editor.fabric.lowerCanvasEl;

                    render = {
                        canvas_name: piece.canvas_name,
                        piece: piece,
                        pieceCache: pieceCache,
                        sizesCache: sizesCache,
                        status: "",
                        loops: [],
                        scale: this.scale,
                        editor: editor,
                        canvas: canvas,
                    };


                    canvas.style.width = 100 * (piece.canvas_width / piece.outer_width) + "%";
                    canvas.style.height = 100 * (piece.canvas_height / piece.outer_height) + "%";
                    canvas.style.left = 100 * (piece.canvas_left / piece.outer_width) + "%";
                    canvas.style.top = 100 * (piece.canvas_top / piece.outer_height) + "%";
                    canvas.style.transform = `rotate(${piece.canvas_rotate}deg)`;
                    canvas.style.zIndex = this.pieces.indexOf(piece) + 1;

                    this.render.set(piece, render)
                    this.$refs.layer.appendChild(canvas);
                    return render.editor.renderLayers(piece.layers);
                } else {


                    // 改变了大小
                    return new Promise((resolve) => {
                        option.design_layers = piece.layers;

                        render.scale = this.scale;
                        render.pieceCache = pieceCache;
                        render.sizesCache = sizesCache;
                        render.loops.push((e) => resolve());
                        render.editor.reset(option);
                        render.canvas.style.width = 100 * (piece.canvas_width / piece.outer_width) + "%";
                        render.canvas.style.height = 100 * (piece.canvas_height / piece.outer_height) + "%";
                        render.canvas.style.left = 100 * (piece.canvas_left / piece.outer_width) + "%";
                        render.canvas.style.top = 100 * (piece.canvas_top / piece.outer_height) + "%";
                        render.canvas.style.transform = `rotate(${piece.canvas_rotate}deg)`;

                        render.editor.renderLayers().then((e) => {
                            render.loops.map((cb) => cb());
                            render.loops = [];
                        });
                    });
                }
            }
        },
        openMedia () {
            this.$emit('global:DESIGN_OPEN_MEDIA');
        },

        // 初始化
        init () {
            if (this.$refs.layer && this.activeSurface) {
                const rect = this.$refs.layer.getBoundingClientRect();
                const surface = this.activeSurface;
                const pieces = surface.pieces || [];
                const active = new Map(pieces.map((i) => [i.canvas_name, i]))

                this.scale = 2 * Math.max(rect.width / surface.outer_width, rect.height / surface.outer_height);

                // this.setMask();
                // this.updateMask(this.activePiece);
                this.pieces.map((piece) => {
                    let render = this.render.get(piece)
                    if (active.get(piece.canvas_name)) {
                        render && (render.canvas.style.display = "block");
                        this.updatePiece(piece);
                    } else {
                        render && (render.canvas.style.display = "none");
                    }
                });

            } else {
                const surface = this.activeSurface || {};
                const pieces = surface.pieces || [];
                this.scale = 1;
                // this.setMask();
                pieces.map((piece) => this.updatePiece(piece));
                // this.updateMask(this.activePiece);
            }
        },

        resize () {
            this.init();
            this.updateMask(this.activePiece, true)
        }

    },
    mounted () {
        this.init();
        this.$nextTick(e => this.updateMask(this.activePiece))
        this.$on("global:DESIGN_CLEANUP", () => this.$nextTick(() => this.init()));
    },
    beforeDestroy () {
        this.render = new Map();
        this.$refs.layer && (this.$refs.layer.innerHTML = "");
        // this.mask = null;
    },
};
</script>

<style lang="scss" scoped>
.editor-render {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 1;
}
.editor-render-layer {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: 2;
    &::v-deep {
        canvas {
            position: absolute;
            top: 0;
            left: 0;
        }
    }
}

.editor-gridline-border {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    border: 1px dashed #239ac2;
    box-sizing: border-box;
    z-index: 2;
    pointer-events: none;

    // border: 1px solid;
    // border-image: repeating-linear-gradient(
    //         -45deg,
    //         #239ac2,
    //         #239ac2 1px,
    //         rgba(255, 255, 255, 0.5) 2px,
    //         rgba(255, 255, 255, 0.5) 3px
    //     )
    //     4;
}

.editor-gridline-line {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    pointer-events: none;
    z-index: 1;

    span {
        position: absolute;
        box-sizing: border-box;
        border-left: 1px solid rgb(35, 154, 194, 0.55);
        border-top: 1px solid rgb(35, 154, 194, 0.55);
    }
    svg {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        opacity: 0.8;
    }
}

.editor-render-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    overflow: hidden;
    canvas,
    svg {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

    svg {
        display: none;
    }

    &[name='Neck Label Inner'] {
        svg {
            display: block;
        }
        canvas {
            opacity: 0;
        }
    }
}

.editor-gridline-nodata {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background: rgba(220, 246, 254, 0.9);
    display: flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
    padding: 10px;
    pointer-events: all;
    z-index: 5;
    cursor: pointer;
    border: 1px dashed #239ac2;

    svg {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        max-width: 100%;
        max-height: 100%;
        width: 86px;
        height: 86px;
        fill: #5dd3fb;
        transition: all 0.1s;
    }

    &:hover svg {
        width: 110px;
        height: 110px;
    }
}
</style>
